import GameObject from "./GameObject";
import Utils from "./utils";
import GameConst from "./GameConst";

export default class ClickableObject extends GameObject {
    constructor(t) {
        super();
        if (typeof t === "undefined") {
            t = null
        }
        this.shape = -1;
        this.radius = 0;
        this.shift = new Laya.Point;
        this.rect = new Laya.Rectangle;
        this.lastClickTime = -1;
        if (t)
            this.sprite = t
    }

    setCircle(radius, offsetX, offsetY) {
        if (typeof offsetX === "undefined") {
            offsetX = 0
        }
        if (typeof offsetY === "undefined") {
            offsetY = 0
        }
        this.shape = ClickableObject.CIRCLE_SHAPE;
        this.radius = radius;
        this.shift.x = offsetX;
        this.shift.y = offsetY
    };

    setRect(x, y, width, height) {
        this.shape = ClickableObject.RECT_SHAPE;
        this.rect.x =x;
        this.rect.y = y;
        this.rect.width = width;
        this.rect.height = height;
    }
}


ClickableObject.prototype.checkClick = function (stX, stY) {
    if (this.sprite && this.shape >= 0 && this.sprite.visible && this.sprite.parent && this.sprite.parent.visible) {
        var r = this.sprite.localToGlobal(Utils.cjp(0,0));
        switch (this.shape) {
            case ClickableObject.CIRCLE_SHAPE:
                var distance = Utils.distanceBetweenPoints(r.x + this.shift.x, r.y + this.shift.y, stX, stY);
                return  distance<= this.radius;
            case ClickableObject.RECT_SHAPE:
                // stX += this.rect.width/2;
                // stY += this.rect.height/2;
                // return e >= r.x + this.rect.x && n >= r.y + this.rect.y && e <= r.x + this.rect.x + this.rect.width && n <= r.y + this.rect.y + this.rect.height
                return stX >= r.x  && stY >= r.y-this.rect.height/2  && stX <= r.x + this.rect.width && stY <= r.y + this.rect.height;
        }
    }
    return false
};
ClickableObject.prototype.onClick = function () {
    if (this.callback) {
        var e = GameConst.game.gameTime;
        if (Math.abs(e - this.lastClickTime) > .3) {
            this.lastClickTime = e;
            if(thisObj){
                this.callback.call(thisObj);
            }else{
                this.callback()
            }
        }
    }
};
ClickableObject.prototype.updateRectScale = function () {
    var e = this.sprite.getBounds();
    this.setRect(e.x * this.sprite.scaleX, e.y * this.sprite.scaleY, e.width * this.sprite.scaleX, e.height * this.sprite.scaleY)
};
ClickableObject.CIRCLE_SHAPE = 0;
ClickableObject.RECT_SHAPE = 1;